/**
 * Created by Jan-Home on 2016/11/15 0015.
 */

const _ = require('lodash');

// @link https://github.com/glena/webpack-custom-var-library-name-plugin
function CustomVarLibraryNamePlugin(mappings) {
	this.mappings = mappings || {};
}

var quote = function(str) {
	return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};

CustomVarLibraryNamePlugin.prototype.apply = function(compiler) {
	var _this = this;

	compiler.plugin("compilation", function(compilation) {

		var mainTemplate = compilation.mainTemplate;

		mainTemplate.plugin('asset-path', function(path, data) {
			_.forEach(_this.mappings, function(replaceName, rawName) {
				var regexp = new RegExp(quote('root["'+rawName+'"]'));
				if (path.match(regexp)) {
					path = path.replace(rawName, replaceName);
				}
			});
			return path;
			// return path.indexOf('root[') === 0 ? 'root["' + _this.options.name + '"]' : path;
		});
	});
};

module.exports = CustomVarLibraryNamePlugin;